package com.xhsj.user.advice;

import com.alibaba.fastjson.JSON;
import com.xhsj.user.hr.system.service.TbOperationRecordsService;
import com.xhsj.user.hr.system.web.FileController;
import com.xhsj.user.utils.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

/**
 * 返回拦截处理
 * @author suxiaolin
 * @date 2021/4/28 17:09
 */
@Slf4j
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice {

    @Autowired
    private TbOperationRecordsService tbOperationRecordsService;


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {

        Method method = methodParameter.getMethod();
        Class<?> declaringClass = method.getDeclaringClass();

        /*排除文件下载接口*/
        Class<FileController> fileControllerClass = FileController.class;
        if (declaringClass == fileControllerClass) {
            String name = method.getName();
            if ("getFile".equals(name) || "display".equals(name)) {
                return false;
            }
        }

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        Method method=methodParameter.getMethod();
        String url=serverHttpRequest.getURI().toASCIIString();
        log.info("{}.{},url={},result={}",method.getDeclaringClass().getSimpleName(),method.getName(),url,JSON.toJSONString(o));

        try {
            if (url.endsWith("/oauth/token")) {
                tbOperationRecordsService.saveLoginRecords(o);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }
}
